import router, { privateRoutes } from '@/router'

const routeObj = {
  children: privateRoutes
}

/**
 * 属性路由筛选 code必须只有在最低层才有用
 *  @param routes 路由表
 *  @param selectedCodes 选中的路由的code集合
 * **/
function filterTreeData (routes, selectedCodes) {
  // 如果当前节点是叶节点并且它的ID在selectedCodes中，返回当前节点
  if (!routes.children) {
    if (!routes.meta?.code) return routes
    const codes = routes.meta.code.split(',')
    return codes.some(c => selectedCodes.includes(c)) ? routes : null
  }
  // 递归处理子节点
  const filteredChildren = routes.children
    .map(child => filterTreeData(child, selectedCodes))
    .filter(child => child !== null)

  // 如果有子节点被保留，返回当前节点，否则返回null
  if (filteredChildren.length > 0) {
    return { ...routes, children: filteredChildren }
  } else {
    return null
  }
}

/**
 * 设置路由
 * **/
export const setRoutes = (codeList) => {
  const routes = filterTreeData(routeObj, codeList)
  if (routes) {
    const menu = routes.children
    menu.forEach(v => {
      router.addRoute(v)
    })
  }
}

/**
 * 移除路由
 * **/
export const removeRoutes = (codeList) => {
  const routes = filterTreeData(routeObj, codeList)
  if (routes) {
    const menu = routes.children
    menu.forEach(v => {
      router.removeRoute(v)
    })
  }
}
